/**
 * 新闻详情页面
 *
 * 这个页面展示了：
 * 1. 动态路由参数获取
 * 2. 新闻详情展示
 * 3. 相关新闻推荐
 * 4. 社交分享功能
 * 5. 面包屑导航
 */
import React, { useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useNewsDetail, useNews } from '@/hooks/useNews';
import { toast } from 'sonner';

export default function NewsDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  // 获取新闻详情
  const {
    data: news,
    isLoading,
    error,
    isError
  } = useNewsDetail(parseInt(id || '0'));

  // 获取相关新闻（同分类的其他新闻）
  const {
    data: relatedNewsData
  } = useNews({
    category: news?.category,
    size: 4,
    published_only: true
  });

  // 错误处理
  useEffect(() => {
    if (isError) {
      toast.error('新闻不存在或已被删除');
      navigate('/news');
    }
  }, [isError, navigate]);

  // 分享功能
  const handleShare = (platform: string) => {
    const url = window.location.href;
    const title = news?.title || '';

    let shareUrl = '';

    switch (platform) {
      case 'wechat':
        // 微信分享通常需要微信SDK，这里只是示例
        toast.info('请复制链接手动分享到微信');
        navigator.clipboard.writeText(url);
        break;
      case 'weibo':
        shareUrl = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`;
        window.open(shareUrl, '_blank');
        break;
      case 'qq':
        shareUrl = `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`;
        window.open(shareUrl, '_blank');
        break;
      case 'copy':
        navigator.clipboard.writeText(url);
        toast.success('链接已复制到剪贴板');
        break;
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <div className="container mx-auto px-4 py-8">
          <div className="max-w-4xl mx-auto">
            {/* 骨架屏 */}
            <div className="animate-pulse">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-6"></div>
              <div className="h-8 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="h-4 bg-gray-200 rounded w-1/2 mb-8"></div>
              <div className="h-64 bg-gray-200 rounded mb-8"></div>
              <div className="space-y-4">
                <div className="h-4 bg-gray-200 rounded"></div>
                <div className="h-4 bg-gray-200 rounded"></div>
                <div className="h-4 bg-gray-200 rounded w-5/6"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // 如果没有新闻数据，返回空（错误处理会重定向）
  if (!news) {
    return null;
  }

  // 过滤相关新闻（排除当前新闻）
  const relatedNews = relatedNewsData?.items?.filter(item => item.id !== news.id) || [];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 面包屑导航 */}
      <div className="bg-white border-b">
        <div className="container mx-auto px-4 py-4">
          <nav className="flex items-center space-x-2 text-sm">
            <Link to="/" className="text-blue-600 hover:text-blue-800">
              首页
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <Link to="/news" className="text-blue-600 hover:text-blue-800">
              新闻动态
            </Link>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-600">{news.category}</span>
            <i className="fa-solid fa-chevron-right text-gray-400"></i>
            <span className="text-gray-900 truncate max-w-xs">{news.title}</span>
          </nav>
        </div>
      </div>

      <div className="container mx-auto px-4 py-8">
        <div className="max-w-4xl mx-auto">
          {/* 新闻头部 */}
          <article className="bg-white rounded-lg shadow-md overflow-hidden mb-8">
            {/* 新闻标题和元信息 */}
            <div className="p-8">
              <div className="flex items-center mb-4">
                <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                  {news.category}
                </span>
                {news.is_featured && (
                  <span className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800 ml-2">
                    <i className="fa-solid fa-star mr-1"></i>
                    置顶
                  </span>
                )}
              </div>

              <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-6 leading-tight">
                {news.title}
              </h1>

              <div className="flex items-center justify-between text-sm text-gray-600 mb-6 pb-6 border-b">
                <div className="flex items-center space-x-6">
                  <div className="flex items-center">
                    <i className="fa-solid fa-user mr-2"></i>
                    <span>{news.author}</span>
                  </div>
                  <div className="flex items-center">
                    <i className="fa-solid fa-calendar mr-2"></i>
                    <span>{formatDate(news.published_at)}</span>
                  </div>
                  <div className="flex items-center">
                    <i className="fa-solid fa-eye mr-2"></i>
                    <span>{news.view_count} 次浏览</span>
                  </div>
                </div>

                {/* 分享按钮 */}
                <div className="flex items-center space-x-2">
                  <span className="text-gray-500">分享：</span>
                  <button
                    type="button"
                    onClick={() => handleShare('wechat')}
                    className="w-8 h-8 bg-green-500 text-white rounded-full flex items-center justify-center hover:bg-green-600 transition-colors"
                    title="分享到微信"
                  >
                    <i className="fa-brands fa-weixin text-sm"></i>
                  </button>
                  <button
                    type="button"
                    onClick={() => handleShare('weibo')}
                    className="w-8 h-8 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                    title="分享到微博"
                  >
                    <i className="fa-brands fa-weibo text-sm"></i>
                  </button>
                  <button
                    type="button"
                    onClick={() => handleShare('copy')}
                    className="w-8 h-8 bg-gray-500 text-white rounded-full flex items-center justify-center hover:bg-gray-600 transition-colors"
                    title="复制链接"
                  >
                    <i className="fa-solid fa-link text-sm"></i>
                  </button>
                </div>
              </div>

              {/* 新闻摘要 */}
              {news.excerpt && (
                <div className="bg-blue-50 border-l-4 border-blue-400 p-4 mb-6">
                  <p className="text-blue-800 font-medium">{news.excerpt}</p>
                </div>
              )}
            </div>

            {/* 封面图片 */}
            {/* {news.cover_image && (
              <div className="px-8 mb-8">
                <img
                  src={news.cover_image}
                  alt={news.title}
                  className="w-full h-64 md:h-96 object-cover rounded-lg"
                  onError={(e) => {
                    const target = e.target as HTMLImageElement;
                    target.style.display = 'none';
                  }}
                />
              </div>
            )} */}

            {/* 新闻内容 */}
            <div className="px-8 pb-8">
              <div
                className="prose prose-lg max-w-none"
                dangerouslySetInnerHTML={{ __html: news.content }}
              />
            </div>
          </article>

          {/* 相关新闻推荐 */}
          {relatedNews.length > 0 && (
            <div className="bg-white rounded-lg shadow-md p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">相关新闻</h2>
              <div className="grid md:grid-cols-2 gap-6">
                {relatedNews.slice(0, 4).map((relatedNews) => (
                  <Link
                    key={relatedNews.id}
                    to={`/news/${relatedNews.id}`}
                    className="group block"
                  >
                    <div className="flex space-x-4">
                      {relatedNews.cover_image ? (
                        <img
                          src={relatedNews.cover_image}
                          alt={relatedNews.title}
                          className="w-20 h-20 object-cover rounded-lg flex-shrink-0 group-hover:opacity-80 transition-opacity"
                          onError={(e) => {
                            const target = e.target as HTMLImageElement;
                            target.src = '</text></svg>';
                          }}
                        />
                      ) : (
                        <div className="w-20 h-20 bg-gray-200 rounded-lg flex-shrink-0 flex items-center justify-center">
                          <i className="fa-solid fa-newspaper text-gray-400"></i>
                        </div>
                      )}
                      <div className="flex-1 min-w-0">
                        <h3 className="text-sm font-medium text-gray-900 group-hover:text-blue-600 transition-colors line-clamp-2 mb-2">
                          {relatedNews.title}
                        </h3>
                        <div className="flex items-center text-xs text-gray-500 space-x-2">
                          <span>{relatedNews.category}</span>
                          <span>•</span>
                          <span>{new Date(relatedNews.published_at).toLocaleDateString('zh-CN')}</span>
                          <span>•</span>
                          <span>{relatedNews.view_count} 浏览</span>
                        </div>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>

              <div className="text-center mt-8">
                <Link
                  to="/news"
                  className="inline-flex items-center px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <i className="fa-solid fa-newspaper mr-2"></i>
                  查看更多新闻
                </Link>
              </div>
            </div>
          )}

          {/* 返回按钮 */}
          <div className="text-center mt-8">
            <button
              type="button"
              onClick={() => navigate(-1)}
              className="inline-flex items-center px-6 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
            >
              <i className="fa-solid fa-arrow-left mr-2"></i>
              返回上一页
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}